package com.sxbang.friday.controller;

import com.sxbang.friday.base.result.PageTableRequest;
import com.sxbang.friday.base.result.ResponseCode;
import com.sxbang.friday.base.result.Results;
import com.sxbang.friday.dto.UserDto;
import com.sxbang.friday.model.SysUser;
import com.sxbang.friday.service.UserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {


    @Autowired
    private UserService userService;

    @RequestMapping("/{username}")
    @ResponseBody
    public SysUser user(@PathVariable String username) {

        log.info("hello" + username);
        return userService.getUser(username);//返回一个查询一个getUser
    }

    @RequestMapping("/admin")
    public String admin() {
        return "user/admin-list";
    }

    @RequestMapping("/user/{name}")
    public String name(@PathVariable String name, Model model) {
        model.addAttribute("name", name);
        System.out.println("testPathVariable:" + name);
        return "index";
    }

    @RequestMapping("/list")
    @ResponseBody//url中会默认的传入page和limit
    public Results<SysUser> user(PageTableRequest pageTableRequest) {//返回一个Result<SysUser>//还需要定义一个类计算当前页和起始页和需要返回的页数的类PageTableRequest
        pageTableRequest.countOffset();//如如果的当前页没有指定，获取显示的行数没有指定，行数为0
        return userService.selectUser(pageTableRequest.getOffset(), pageTableRequest.getLimit());//出入参数起始位置，和查
    }

    @GetMapping("/add")
    public String userAdd(Model model) {
        model.addAttribute(new SysUser());
        return "user/admin-add";
    }

    //    @RequestMapping("/adds")
    @PostMapping("/add")
    @ResponseBody//返回json数据
    public Results<SysUser> saveUser(UserDto userDto, Integer roleId/*,HttpSession session*/) {
        //验证手机号不重复
        SysUser sysUser = null;
        sysUser = userService.getUserByPhone(userDto.getTelephone());
        if (sysUser != null && !(sysUser.getId().equals(userDto.getId()))) {//如果手机手机号存在就返回一个错误的Result
            return Results.failure(ResponseCode.EMAIL_REPEAT.getCode(), ResponseCode.EMAIL_REPEAT.getMessage());
        }
        userDto.setStatus(1);//用户创建自动启用
        userDto.setNickname("11");
        // md5加密的操作
        //创建用户
        //使用md5加密
        //提交用户信息
        userDto.setPassword(DigestUtils.md5Hex(userDto.getPassword()));
        return userService.save(userDto, roleId);
    }

    String pattern = "yyyy-MM-dd";
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(pattern), true));
    }

    @GetMapping("/edit")
    public String userEdit(Model model,SysUser sysUser) {
        //通过id查询到该用户
        model.addAttribute(userService.getUserById(sysUser.getId()));
        return "user/admin-edit";
    }

    @PostMapping("/edit")
    @ResponseBody//返回json数据
    public Results<SysUser> updateUser(UserDto userDto, Integer roleId/*,HttpSession session*/) {//UserDto用于业务层传值
        //修改和新增差不多，修改后手机号也不能重复
        SysUser sysUser = null;
        sysUser = userService.getUserByPhone(userDto.getTelephone());
        if (sysUser != null && !(sysUser.getId().equals(userDto.getId()))) {//如果手机手机号存在就返回一个错误的Result
            return Results.failure(ResponseCode.PHONE_REPEAT.getCode(), ResponseCode.PHONE_REPEAT.getMessage());
        }

        return userService.updateUser(userDto,roleId);
    }
//    @RequestMapping("/p")
//    public String hehe(HttpSession session) {
//        SysUser sysUser = new SysUser("6", "2", "3", "4", "5", "6", "7", new Date(), 1, 1);
//        session.setAttribute("sysUser", sysUser);
//        return "redirect:/user/adds";
//    }
    @GetMapping("/delete")
    @ResponseBody
    public Results deleteUser(UserDto userDto){
        int count = userService.deleteUser(userDto.getId());
        if(count > 0){
            return Results.success();
        }else{
            return Results.failure();
        }
    }

    @RequestMapping("/findUserByFuzzyUsername")
    @ResponseBody//url中会默认的传入page和limit
    public Results<SysUser> findUserByFuzzyUsername(PageTableRequest pageTableRequest,String username) {//返回一个Result<SysUser>//还需要定义一个类计算当前页和起始页和需要返回的页数的类PageTableRequest
        System.out.println(pageTableRequest+"---------------"+username);
        pageTableRequest.countOffset();//如如果的当前页没有指定，获取显示的行数没有指定，行数为0
        return userService.getUserByFuzzyUsername(username,pageTableRequest.getOffset(), pageTableRequest.getLimit());//出入参数起始位置，和查
    }
}
